package com.lechuang.ssgou.view.activity.tipoff;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.format.DateUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.lechuang.ssgou.R;
import com.lechuang.ssgou.model.LeCommon;
import com.lechuang.ssgou.model.LocalSession;
import com.lechuang.ssgou.model.bean.ResultBean;
import com.lechuang.ssgou.model.bean.TipoffShowBean;
import com.lechuang.ssgou.presenter.adapter.MyAdapter;
import com.lechuang.ssgou.presenter.net.Netword;
import com.lechuang.ssgou.presenter.net.ResultBack;
import com.lechuang.ssgou.presenter.net.netApi.TipoffShowApi;
import com.lechuang.ssgou.utils.Utils;
import com.lechuang.ssgou.view.activity.ui.LoginActivity;
import com.lechuang.ssgou.view.dialog.FlippingLoadingDialog;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 作者：li on 2017/9/28 20:55
 * 邮箱：961567115@qq.com
 * 修改备注:
 */
public class TipOffActivity extends Activity implements AdapterView.OnItemClickListener {
    Unbinder unbinder;
    //当前页数
    public int page = 1;

    //搜索商品内容
    public String content = "";
    //数据集合
    ArrayList<TipoffShowBean.ListBean> newsList = new ArrayList<>();
    @BindView(R.id.ll_noNet)
    LinearLayout llNoNet; //没有网络
    @BindView(R.id.iv_tryAgain)
    ImageView tryAgain;
    @BindView(R.id.refresh)
    PullToRefreshScrollView refreshScrollView;
    private LocalSession mSession;
    private ResultBean<TipoffShowBean> request;
    private int conditionType;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    public Context mContent = this;

    private boolean _isVisible = true;
    private FlippingLoadingDialog waitDialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_tipoff_comment);
        unbinder= ButterKnife.bind(this);
        initView();
        initData();
    }

    public void initView() {
        recyclerView.setHasFixedSize(true); // 设置固定大小
        recyclerView.setNestedScrollingEnabled(false);
        StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(2,
                StaggeredGridLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(staggeredGridLayoutManager);
        ((TextView)findViewById(R.id.tv_title)).setText("爆料");
        findViewById(R.id.iv_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        refreshScrollView.setOnRefreshListener(refresh);
        mSession = LocalSession.get(this);
        tryAgain.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initData();
            }
        });
    }

    public void initData() {
        showWaitDialog("");
        if (!Utils.isNetworkAvailable(mContent)) {
            hideWaitDialog();
            llNoNet.setVisibility(View.VISIBLE);
            refreshScrollView.setVisibility(View.GONE);
            Utils.show(mContent, getString(R.string.net_error));
            return;
        }
        llNoNet.setVisibility(View.GONE);
        refreshScrollView.setVisibility(View.VISIBLE);
        Netword.getInstance().getApi(TipoffShowApi.class)
                .getTipoff(content, conditionType, page)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(handler);
         hideWaitDialog();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
    }

    public PullToRefreshBase.OnRefreshListener2 refresh = new PullToRefreshBase.OnRefreshListener2() {
        @Override
        public void onPullDownToRefresh(PullToRefreshBase refreshView) {
            String label = DateUtils.formatDateTime(
                    mContent.getApplicationContext(),
                    System.currentTimeMillis(),
                    DateUtils.FORMAT_SHOW_TIME
                            | DateUtils.FORMAT_SHOW_DATE
                            | DateUtils.FORMAT_ABBREV_ALL);
            // 显示最后更新的时间
            refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
            page = 1;
            initData();
            refreshScrollView.onRefreshComplete();
        }

        @Override
        public void onPullUpToRefresh(PullToRefreshBase refreshView) {
            String label = DateUtils.formatDateTime(
                    mContent.getApplicationContext(),
                    System.currentTimeMillis(),
                    DateUtils.FORMAT_SHOW_TIME
                            | DateUtils.FORMAT_SHOW_DATE
                            | DateUtils.FORMAT_ABBREV_ALL);
            // 显示最后更新的时间
            refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
            page += 1;
            // 模拟加载任务
            initData();
            refreshScrollView.onRefreshComplete();
        }
    };
    //数据适配



    //处理信息的handler
    ResultBack handler = new ResultBack<TipoffShowBean>(this) {
        @Override
        public void successed(TipoffShowBean result) {
            TipoffShowBean request = result;
            if (request == null) {
                return;
            }
            List<TipoffShowBean.ListBean> list = request.list;
            refreshScrollView.setMode(list.size() > 0 ? PullToRefreshBase.Mode.BOTH : PullToRefreshBase.Mode.PULL_FROM_START);
            if (page != 1 && list.toString().equals("[]")) {            //数据没有了
                Utils.show(TipOffActivity.this, "亲!已经到底了");
                hideWaitDialog();
                refreshScrollView.onRefreshComplete();
                return;
            }
//            for (int i = 0; i < list.size(); i++) {     //数据加入
//                 newsList.add(list.get(i));
//            }
            if (page == 1) {                 //加载第一页
                newsList.clear();
                newsList.addAll(list);
                recyclerView.setAdapter(myAdapter);
            } else {
                newsList.addAll(list);
            }
            myAdapter.notifyDataSetChanged();
            hideWaitDialog();
        }
    };

public MyAdapter myAdapter=new MyAdapter(newsList, new MyAdapter.RecycleViewListener() {
    @Override
    public void itemClik(TipoffShowBean.ListBean listBean) {
        if (PreferenceManager.getDefaultSharedPreferences(TipOffActivity.this).getBoolean(LeCommon.KEY_HAS_LOGIN, false)) {
            Intent intent = new Intent(TipOffActivity.this, StoryDetailActivity.class);
            intent.putExtra("id", listBean.id);
            startActivity(intent);
        } else {
            startActivity(new Intent(TipOffActivity.this, LoginActivity.class));
        }
    }
});
    /**
     * @author li
     * 邮箱：961567115@qq.com
     * @time 2017/9/29  15:38
     * @describe 列表条目展示
     */
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (PreferenceManager.getDefaultSharedPreferences(mContent).getBoolean(LeCommon.KEY_HAS_LOGIN, false)) {
            Intent intent = new Intent(mContent, StoryDetailActivity.class);
            intent.putExtra("id", newsList.get(position).id);
            startActivity(intent);
        } else {
            startActivity(new Intent(mContent, LoginActivity.class));
        }
    }

    public FlippingLoadingDialog showWaitDialog(String message) {
        if (_isVisible) {
            if (waitDialog == null) {
                waitDialog = new FlippingLoadingDialog(mContent, message);
            }
            if (waitDialog != null) {
                waitDialog.setText(message);
                waitDialog.show();
            }
            return waitDialog;
        }
        return null;
    }

    public void hideWaitDialog() {
        if (_isVisible && waitDialog != null) {
            try {
                if (waitDialog.isShowing())
                    waitDialog.dismiss();
                waitDialog = null;
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

}

